package lc20240430;

import java.util.HashMap;
import java.util.Map;

public class Demo2 {
    public static void main(String[] args) {
//        String s = "aba";
//        System.out.println(judgeRepeatString(s));
        String str = "tmmzuxt";
//        System.out.println(str.length());
        System.out.println(lengthOfLongestSubstring1(str));
    }

    public static int lengthOfLongestSubstring(String s) {
        //最大长度
        int maxLen = 0;
        if (s.length() == 0) {
            return maxLen;
        }
        if (s.length() == 1) {
            return 1;
        }

        int i = 0;
        int j = 0;
        int n = s.length();
        while (i < n && j <= n) {

            String temp = s.substring(i, j);
            //判断是否有重复子串
            if (judgeRepeatString(temp)) {
                i++;
                //j = i;
            } else {
                maxLen = Math.max(j - i, maxLen);
                j++;
            }
        }
        return maxLen;

    }

    public static int lengthOfLongestSubstring1(String s) {
        //最大长度
        int maxLen = 0;
        if (s.length() == 0) {
            return maxLen;
        }
        if (s.length() == 1) {
            return 1;
        }

        Map<Character, Integer> map = new HashMap<>();

        //窗口开始位置
        int i = 0;
        int n = s.length();
        for (int j = 0; j < n; j++) {
            char c = s.charAt(j);
            if (map.containsKey(c)) {
                //更新i位置
                i = Math.max(i, map.get(c) + 1);
            }
            map.put(c, j);
            maxLen = Math.max(maxLen, j - i + 1);
        }
        return maxLen;
    }

    public static boolean judgeRepeatString(String s) {
        Map<Character, Boolean> map = new HashMap<>();
        for (char c : s.toCharArray()) {
            if (map.containsKey(c)) {
                return true;
            } else {
                map.put(c, true);
            }
        }
        return false;
    }
}
